package com.cjp.run.init;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cjp.run.Application;
import com.cjp.utils.FileUtils;
import com.cjp.utils.SymmetricEncoder;
@Component
public class InitBean implements InitializingBean{
	private static Map<String,SendThread> threadMap=new HashMap<String,SendThread>();
	@Override
	public void afterPropertiesSet() throws Exception {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					try {
						JSONObject userJson=FileUtils.readUser();
						if(userJson!=null&&userJson.containsKey("data")){
							JSONArray userJsonArray=userJson.getJSONArray("data");
							if(userJsonArray!=null){
								for(int k=0;k<userJsonArray.size();k++){
									JSONObject user=userJsonArray.getJSONObject(k);
									FileUtils.currentUser.set(user.getString("username"));
									JSONArray appjsonArray=FileUtils.readApp("app");
									if(appjsonArray!=null){
										for(int z=0;z<appjsonArray.size();z++){
											JSONObject appJson=appjsonArray.getJSONObject(z);
											FileUtils.currentAppidThread.set(appJson.getString("APPID"));
											FileUtils.currentAppAppsecretThread.set(SymmetricEncoder.AESDncode("APPSECRETKEY", appJson.getString("APPSECRET")));
											Calendar calendar=Calendar.getInstance();
											SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
											SimpleDateFormat hhDateFormat=new SimpleDateFormat("yyyyMMddHH");
											JSONArray jsonArray=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray==null){
												jsonArray=new JSONArray();
											}
											calendar.add(Calendar.DAY_OF_MONTH, -1);
											JSONArray jsonArray1=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray1!=null){
												for(int i=0;i<jsonArray1.size();i++){
													jsonArray.add(jsonArray1.get(i));
												}
											}
											
											calendar.add(Calendar.DAY_OF_MONTH, -1);
											JSONArray jsonArray2=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray2!=null){
												for(int i=0;i<jsonArray2.size();i++){
													jsonArray.add(jsonArray2.get(i));
												}
											}
											
											calendar.add(Calendar.DAY_OF_MONTH, -1);
											JSONArray jsonArray3=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray3!=null){
												for(int i=0;i<jsonArray3.size();i++){
													jsonArray.add(jsonArray3.get(i));
												}
											}
											
											calendar.add(Calendar.DAY_OF_MONTH, -1);
											JSONArray jsonArray4=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray4!=null){
												for(int i=0;i<jsonArray4.size();i++){
													jsonArray.add(jsonArray4.get(i));
												}
											}
											calendar.add(Calendar.DAY_OF_MONTH, -1);
											JSONArray jsonArray5=FileUtils.read(dateFormat.format(calendar.getTime()));
											if(jsonArray5!=null){
												for(int i=0;i<jsonArray5.size();i++){
													jsonArray.add(jsonArray5.get(i));
												}
											}
											if(jsonArray!=null&&jsonArray.size()>0){
												//获取用户列表,每小时更新一次
												Date userDate=new Date();
												JSONObject json=FileUtils.readTemplate("user", hhDateFormat.format(userDate));
												if(json==null){
													try {
														String result=Application.getUserList();
														json=JSONObject.parseObject(result);
														if(!json.containsKey("errcode")){
															FileUtils.write("user", hhDateFormat.format(userDate), json.toString(), false);
														}else{
															Thread.sleep(1000*10);
														}
													} catch (Exception e) {
														e.printStackTrace();
														continue;
													}
												}
												
												for(int i=0;i<jsonArray.size();i++){
													JSONObject jsonObject=jsonArray.getJSONObject(i);
													if(jsonObject.getString("isSend").equals("0")){//0为未发送
														SimpleDateFormat d=new SimpleDateFormat("yyyy-MM-dd HH:mm");
														Date date=d.parse(jsonObject.getString("setSendTime"));
														if(date.after(new Date())){
															continue;
														}
														System.out.println(jsonArray.toString());
														JSONArray openidJson=json.getJSONObject("data").getJSONArray("openid");
														for(int j=0;j<openidJson.size();j++){
															String openid=openidJson.getString(j);
															/*String r=null;
															try {
																r=Application.sendWechatmsgToUser(openid, jsonObject.getString("templateId"),jsonObject.getString("clickurl") , jsonObject.getString("topcolor"), new JSONObject(jsonObject.getString("data")));
															} catch (Exception e) {
																e.printStackTrace();
															}finally{
																System.out.println("发送："+openid+";发送结果："+r);
															}*/
															
															SendMessage sendMessage=new SendMessage();
															sendMessage.setAppid(FileUtils.currentAppidThread.get());
															sendMessage.setAppsecret(FileUtils.currentAppAppsecretThread.get());
															sendMessage.setOpenid(openid);
															sendMessage.setDataJson(jsonObject);
															
															SendThread sendThread=threadMap.get(FileUtils.currentAppidThread.get());
															if(sendThread==null){
																sendThread=new SendThread();
																threadMap.put(FileUtils.currentAppidThread.get(), sendThread);
																sendThread.add(sendMessage);
																new Thread(sendThread).start(); 
															}else{
																sendThread.add(sendMessage);
															}
														}
														jsonObject.put("isSend", "1");
														jsonObject.put("sendTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
														
														FileUtils.sendWrite(jsonObject.getString("id"),jsonObject.toString(),jsonObject.getString("createTime"));
													}
												}
											}
										}
									}else{
										Thread.sleep(2000);
									}
								}
							}
						}else{
							Thread.sleep(2000);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}).start();
	}

}

class SendThread implements Runnable{
	private ConcurrentLinkedQueue<SendMessage> queue=new ConcurrentLinkedQueue<SendMessage>();
	
	@Override
	public void run() {
		while(true){
			try {
				SendMessage sendMessage;
				if((sendMessage=queue.poll())!=null){
					FileUtils.currentAppidThread.set(sendMessage.getAppid());
					FileUtils.currentAppAppsecretThread.set(sendMessage.getAppsecret());
					
					String r=null;
					try {
						r=Application.sendWechatmsgToUser(sendMessage.getOpenid(), sendMessage.getDataJson().getString("templateId"),sendMessage.getDataJson().getString("clickurl") , sendMessage.getDataJson().getString("topcolor"), JSONObject.parseObject(sendMessage.getDataJson().getString("data")));
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						System.out.println("发送："+sendMessage.getOpenid()+";发送结果："+r);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void add(SendMessage m){
		queue.offer(m);
	}
}

class SendMessage{
	private String appid;
	private String appsecret;
	private String openid;
	private JSONObject dataJson;
	public String getAppid() {
		return appid;
	}
	public void setAppid(String appid) {
		this.appid = appid;
	}
	public String getAppsecret() {
		return appsecret;
	}
	public void setAppsecret(String appsecret) {
		this.appsecret = appsecret;
	}
	public String getOpenid() {
		return openid;
	}
	public void setOpenid(String openid) {
		this.openid = openid;
	}
	public JSONObject getDataJson() {
		return dataJson;
	}
	public void setDataJson(JSONObject dataJson) {
		this.dataJson = dataJson;
	}
}
